import React from 'react';
import { EditOutlined, PlusOutlined } from '@ant-design/icons';
import { Form } from '@ant-design/compatible';
import '@ant-design/compatible/assets/index.css';
import { Card, Button, Input, Switch, Select, message, Row, Col, Table, Divider, Spin } from 'antd';
import { connect } from 'dva';
import router from 'umi/router';
import PageHeaderWrapper from '@/components/PageHeaderWrapper';
import FooterToolbar from '@/components/FooterToolbar';
import styles from '@/utils/utils.less';
import materialStyle from './material.less';
import DictCode from '../../components/DictCode';
import AddMatModal from './AddMatModal';
import JudgeMatModal from './JudgeMatModal';

const { Option } = Select;
const FormItem = Form.Item;

@connect(({ inservicematerial, loading }) => ({
  inservicematerial,
  loading: loading.models.inservicematerial,
}))
@Form.create()
class AddInservicematerials extends React.Component {
  constructor(props) {
    super(props);
    this.state = {
      visJudge: false, // 判断表格属性
      visMaterial: false,
      pagination: false,
      isDisabled: false,
    };
  }

  componentDidMount = () => {
    const { dispatch } = this.props;
    dispatch({
      type: 'inservicematerial/fetchDict',
      payload: ['ENTRY_SER_TYPE', 'YES_NO_FLAG', 'INPUT_TYPE'],
    });
  };

  componentWillUnmount = () => {
    const { dispatch } = this.props;
    const parms = {
      coltFlag: '1',
      titleArr: [true],
      headertitle: ['标题'],
      tValue: [[]],
      newNo: 0,
      tableArr: [{ pageIdEdit: 0, maGpDetails: [] }],
      requestData: [],
      addMetial: [],
      tableJudge: [],
      logicList: [],
      tValues: '1',
      index: 0,
      bigResult: [],
      matPkgId: null,
      areaIds: undefined,
      remark: undefined,
    };
    dispatch({
      type: 'inservicematerial/updateModelData',
      payload: parms,
    });
  };

  // 材料接口
  metrialLocalData = (nowPage, pageNum, { matId, inpType } = {}) => {
    const { dispatch } = this.props;
    const parameter = {
      page: {
        currentPage: nowPage,
        pageSize: pageNum,
      },
      matInfoVo: {
        relSer: 2,
        matId,
        inpType,
      },
    };
    dispatch({
      type: 'inservicematerial/fetchMatListPage',
      payload: parameter,
    });
  };

  changeBig = value => {
    const parameter = {
      relSer: 2,
      matName: value,
    };
    const { dispatch } = this.props;
    dispatch({
      type: 'inservicematerial/fetchMatList',
      payload: parameter,
    });
  };

  matChange = value => {
    const { dispatch, form } = this.props;
    dispatch({
      type: 'inservicematerial/fetchSerTypeList',
      payload: { serType: value },
    }).then(() => {
      // 清空选项
      form.resetFields(['serTypeId']);
    });
  };

  // 选择判断条件
  handleLogicChange = value => {
    const { dispatch } = this.props;
    dispatch({
      type: 'inservicematerial/updateModelData',
      payload: { tValues: value.label, tValueCode: value.key },
    });
  };

  // 头部 input 更换值的处理
  changeValue = (i, v) => {
    const { dispatch } = this.props;
    dispatch({
      type: 'inservicematerial/changeTitle',
      payload: { i, v },
    });
  };

  // 头部标题的 保存
  headersave = i => {
    // 更换修改样式
    const { dispatch } = this.props;
    dispatch({
      type: 'inservicematerial/saveTitle',
      payload: i,
    });
  };

  // 头部标题修改
  changeTitle = i => {
    const { dispatch } = this.props;
    dispatch({
      type: 'inservicematerial/modifyTitle',
      payload: i,
    });
  };

  // 添加分页
  addTable = () => {
    const { inservicematerial } = this.props;
    const { tableArr } = inservicematerial;
    const isDisabled = tableArr.some(c => {
      if (c.maGpDetails) {
        return c.maGpDetails && c.maGpDetails.length === 0;
      }
      return true;
    });

    if (isDisabled) {
      message.warning('温馨提示：您还未配置材料，不能添加分页');
    } else {
      const { dispatch } = this.props;
      dispatch({
        type: 'inservicematerial/addTable',
        payload: {},
      });
    }
  };

  // 判断标题是不是保存
  titleSave = arr => {
    for (let i = 0; i < arr.length; i += 1) {
      if (arr[i] === false) {
        return false;
      }
    }
    return true;
  };

  // 材料不能重复选择
  judgeMatSelect = selectedRows => {
    const { inservicematerial } = this.props;
    const { tableArr } = inservicematerial;
    let isDisabled = true;
    tableArr.forEach(item => {
      if (item.maGpDetails && item.maGpDetails.length) {
        item.maGpDetails.forEach(c => {
          if (c.children && c.children.length) {
            c.children.forEach(chid => {
              if (selectedRows && selectedRows.length) {
                selectedRows.forEach(id => {
                  if (chid.matId === id.matId) {
                    isDisabled = false;
                  }
                });
              }
            });
          }
          if (selectedRows && selectedRows.length) {
            selectedRows.forEach(id => {
              if (c.matId === id.matId) {
                isDisabled = false;
              }
            });
          }
        });
      }
    });
    return isDisabled;
  };

  handleModalVisible = flag => {
    this.setState({
      visMaterial: !!flag,
    });
  };

  handleModalJudgeVisible = flag => {
    this.setState({
      visJudge: !!flag,
    });
  };

  // 材料弹窗
  metrialbox = (e, i) => {
    const { dispatch } = this.props;
    e.stopPropagation();
    e.preventDefault();
    dispatch({
      type: 'inservicematerial/updateModelData',
      payload: { newNo: i },
    });
    this.handleModalVisible(true);
    this.metrialLocalData(1, 5);
  };

  // 添加材料弹框 - 确定按妞事件
  changeOkMaterial = selectedRows => {
    const { dispatch } = this.props;
    if (this.judgeMatSelect(selectedRows)) {
      for (let i = 0; i < selectedRows.length; i += 1) {
        dispatch({
          type: 'inservicematerial/updateTable',
          payload: selectedRows[i],
        });
      }
      this.setState({
        visMaterial: false,
      });
    } else {
      message.warning('温馨提示：材料已存在，不能重复选择！');
    }
  };

  // 添加材料取消
  changeCancelMaterial = () => {
    this.setState({
      visMaterial: false,
    });
  };

  // 显示逻辑
  showLogicList = code => {
    const { dispatch } = this.props;

    dispatch({
      type: 'inservicematerial/fetchJudgeDict',
      payload: { dictCode: code },
    });
  };

  // 添加判断按妞事件 弹框
  addjudge = (record, index) => {
    const { dispatch } = this.props;
    this.handleModalJudgeVisible(true);
    dispatch({
      type: 'inservicematerial/updateModelData',
      payload: { newButton: index, tValues: '1' },
    });
    this.metrialLocalData(1, 5);
    this.showLogicList(record.dictType);
  };

  // 添加判断（确认）
  okJudge = selectedRows => {
    const { inservicematerial, dispatch } = this.props;
    const { tValues, logicList, tValueCode } = inservicematerial;

    if (selectedRows.length) {
      if (this.judgeMatSelect(selectedRows)) {
        for (let i = 0; i < selectedRows.length; i += 1) {
          const obj = {};
          // 对默认选择的判断
          if (tValues === '1') {
            logicList.forEach(item => {
              if (item.itemCode === '1') {
                dispatch({
                  type: 'inservicematerial/updateModelData',
                  payload: { tValues: item.itemName, tValueCode: item.itemCode },
                });
              }
            });
          }
          obj.judgeLogicName = tValues;
          obj.judgeLogicCode = tValueCode;
          obj.matId = selectedRows[i].matId;
          dispatch({
            type: 'inservicematerial/updateTableChild',
            payload: { selectedRows: selectedRows[i], obj },
          });
        }

        this.setState({
          visJudge: false,
        });
      } else {
        message.warning('温馨提示：材料已存在，不能重复选择！');
      }
    } else {
      message.warning('至少选择一条数据！');
    }
  };

  // 添加判断 - 取消
  cancelJudge = () => {
    this.setState({
      visJudge: false,
    });
  };

  // 删除页
  pageDelete = (pageIdEdit, i) => {
    const { dispatch } = this.props;
    dispatch({
      type: 'inservicematerial/updateModelData',
      payload: { newNo: i },
    });
    setTimeout(() => {
      dispatch({
        type: 'inservicematerial/deletePage',
        payload: { i, pageIdEdit },
      });
    }, 0);
  };

  rowData = i => {
    const { dispatch } = this.props;
    dispatch({
      type: 'inservicematerial/updateModelData',
      payload: { newNo: i },
    });
  };

  // 删除行
  onDelete = (record, i) => {
    const { dispatch } = this.props;
    setTimeout(() => {
      dispatch({
        type: 'inservicematerial/deletePageDom',
        payload: { record, i },
      });
    }, 0);
  };

  // 删除
  onDeleteChild = (record, i) => {
    const { dispatch } = this.props;
    setTimeout(() => {
      dispatch({
        type: 'inservicematerial/deletePageChildDom',
        payload: { record, i },
      });
    }, 0);
  };

  // 表单检测 并 提交
  submitAll = e => {
    e.preventDefault();
    const { form, inservicematerial } = this.props;
    const { titleArr } = inservicematerial;
    form.validateFieldsAndScroll((err, values) => {
      if (!err) {
        if (this.titleSave(titleArr)) {
          this.insert(values);
        } else {
          message.warning('标题未保存！');
        }
      }
    });
  };

  insert = values => {
    const { dispatch } = this.props;
    const { inservicematerial } = this.props;
    const { tableArr, headertitle, coltFlag } = inservicematerial;
    const obj = {}; // 每页
    const maGpagesArr = tableArr;
    let isDised = true;
    maGpagesArr.forEach(value => {
      if (!value.maGpDetails || value.maGpDetails.length === 0) {
        isDised = false;
      }
    });
    if (!isDised && String(coltFlag) === '1') {
      message.warning('温馨提示：有未配置的材料！');
    } else {
      maGpagesArr.forEach((item, i) => {
        const Newitem = item;
        Newitem.pageName = headertitle[i];
      });
      const areaArr = [];
      Object.keys(values).forEach(key => {
        if (key !== 'areaIds' && key !== 'serType' && key !== 'remark' && key !== ' serTypeId') {
          maGpagesArr.forEach(item => {
            item.maGpDetails.forEach(id => {
              const NewId = id;
              if (key.split('+')[0] === 'check') {
                if (key.split('+')[1] === NewId.matId) {
                  if (values[key]) {
                    NewId.reqFlag = 1;
                  } else {
                    NewId.reqFlag = 2;
                  }
                }
              }
              if (NewId.children && NewId.children.length) {
                NewId.children.forEach(chId => {
                  const NewChId = chId;
                  if (key.split('+')[0] === 'check') {
                    if (key.split('+')[1] === NewChId.matId) {
                      if (values[key]) {
                        NewChId.reqFlag = 1;
                      } else {
                        NewChId.reqFlag = 2;
                      }
                    }
                  }
                });
              }
            });
          });
        } else if (key === 'areaIds' && values[key]) {
          values[key].forEach(id => {
            areaArr.push(id.key);
          });
        }
      });
      obj.remark = values.remark;
      obj.serType = values.serType;
      obj.serTypeId = values.serTypeId;
      obj.coltFlag = coltFlag;
      obj.areas = areaArr;
      obj.maGpages = String(coltFlag) === '1' ? maGpagesArr : [];
      dispatch({
        type: 'inservicematerial/fetchSave',
        payload: obj,
      });
    }
  };

  submitcancel = () => {
    router.goBack();
  };

  linkRoute = (id, path) =>
    id
      ? router.push(`/materialmanagement/entrymaterialsmanage/${path}?id=${id}`)
      : router.push(`/materialmanagement/${path}`);

  onIsMatFlag = value => {
    const { dispatch, inservicematerial } = this.props;
    const { tableArr } = inservicematerial;
    dispatch({
      type: 'inservicematerial/updateModelData',
      payload: { coltFlag: value },
    });
    if (Number(value) === 1) {
      dispatch({
        type: 'inservicematerial/addTable',
        payload: {},
      });
    } else {
      tableArr.forEach(item => {
        this.pageDelete(item.pageIdEdit, 0);
      });
    }
  };

  render() {
    const { form, inservicematerial, loading } = this.props;
    const {
      coltFlag,
      areaList,
      matList,
      tableArr,
      titleArr,
      headertitle,
      serTypeIdName,
      matPkgId,
      serTypeName,
      areaIds,
      flagList,
      inputType,
      remark,
    } = inservicematerial;

    const { getFieldDecorator } = form;
    const { visMaterial, visJudge, isDisabled, pagination } = this.state;

    const columns = [
      {
        title: '材料名称',
        dataIndex: 'matName',
      },
      {
        title: '输入类型',
        dataIndex: 'inpTypeName',
      },
      {
        title: '是否支持判断',
        dataIndex: 'judgeFlagName',
        onCell: () => ({
          style: {
            textAlign: 'center',
          },
        }),
        onHeaderCell: () => ({
          style: {
            textAlign: 'center',
            fontWeight: 'bold',
          },
        }),
      },
      {
        title: '显示条件',
        dataIndex: 'judgeLogicName',
        render: (text, record) => {
          if (record.judgeLogicName) {
            return <span>{record.judgeLogicName}</span>;
          }
          return <span>--</span>;
        },
      },
      {
        title: '是否必填',
        dataIndex: 'notNullFlag',
        render: (text, record) => (
          <FormItem style={{ margin: 0 }}>
            {getFieldDecorator(
              `check+${record.matId}`,
              { valuePropName: 'checked', initialValue: record[`check+${record.matId}`] },
              {
                rules: [
                  {
                    required: false,
                    message: '请选择',
                  },
                ],
              }
            )(<Switch />)}
          </FormItem>
        ),
      },
      {
        title: '操作',
        dataIndex: 'operation',
        onCell: () => ({
          style: {
            textAlign: 'center',
          },
        }),
        onHeaderCell: () => ({
          style: {
            textAlign: 'center',
            fontWeight: 'bold',
            width: 145,
          },
        }),
        render: (text, record, index) => {
          if (record.judgeLogicName) {
            return <a onClick={() => this.onDeleteChild(record, index)}> 删除 </a>;
          }
          if (record.judgeFlagName === '否') {
            return <a onClick={() => this.onDelete(record, index)}> 删除 </a>;
          }
          return (
            <span>
              <a onClick={() => this.addjudge(record, index)}>添加判断</a>
              <Divider type="vertical" />
              <a onClick={() => this.onDelete(record, index)}> 删除 </a>
            </span>
          );
        },
      },
    ];

    const formItemLayout = {
      labelCol: {
        xs: {
          span: 24,
        },
        sm: {
          span: 8,
        },
      },
      wrapperCol: {
        xs: {
          span: 24,
        },
        sm: {
          span: 16,
        },
      },
    };

    return (
      <PageHeaderWrapper>
        <Spin tip="Loading..." spinning={loading}>
          <Card title="在职服务材料配置" bordered={false}>
            <Form>
              <Row>
                <Col span={8}>
                  <FormItem {...formItemLayout} label="服务类型：">
                    {getFieldDecorator('serType', {
                      rules: [
                        {
                          required: !matPkgId,
                          message: '请选择服务类型',
                        },
                      ],
                    })(
                      matPkgId ? (
                        <div>{serTypeName}</div>
                      ) : (
                        <DictCode
                          allowClear
                          showSearch
                          filterOption={(input, option) =>
                            option.props.children.toLowerCase().indexOf(input.toLowerCase()) >= 0
                          }
                          dictType="ENTRY_SER_TYPE"
                          onSelect={this.matChange}
                        />
                      )
                    )}
                  </FormItem>
                </Col>
                <Col span={8}>
                  <FormItem {...formItemLayout} label="材料类型:">
                    {getFieldDecorator('serTypeId', {
                      rules: [
                        {
                          required: !matPkgId,
                          message: '请选择材料类型',
                        },
                      ],
                    })(
                      matPkgId ? (
                        <div>{serTypeIdName}</div>
                      ) : (
                        <Select
                          style={{ width: '100%' }}
                          placeholder="请选择材料类型"
                          allowClear
                          showSearch
                          filterOption={(input, option) =>
                            option.props.children.toLowerCase().indexOf(input.toLowerCase()) >= 0
                          }
                        >
                          {matList.map(item => (
                            <Option key={item.serTypeId}>{item.serTypeIdName}</Option>
                          ))}
                        </Select>
                      )
                    )}
                  </FormItem>
                </Col>
                <Col span={8}>
                  <FormItem {...formItemLayout} label="地区:">
                    {getFieldDecorator('areaIds', {
                      rules: [
                        {
                          required: true,
                          message: '请选择地区',
                        },
                      ],
                      initialValue: areaIds,
                    })(
                      <Select
                        allowClear
                        showSearch
                        filterOption={(input, option) =>
                          option.props.children.toLowerCase().indexOf(input.toLowerCase()) >= 0
                        }
                        labelInValue
                        mode="multiple"
                        placeholder="请选择地区"
                      >
                        {areaList.map(item => (
                          <Option key={item.areaId}>{item.areaName}</Option>
                        ))}
                      </Select>
                    )}
                  </FormItem>
                </Col>
              </Row>
              <Row>
                <Col span={8}>
                  <FormItem {...formItemLayout} label={<span>是否收取材料</span>}>
                    {getFieldDecorator('coltFlag', {
                      rules: [
                        {
                          required: true,
                          message: '请选择是否收取材料',
                          max: 100,
                        },
                      ],
                      initialValue: coltFlag,
                    })(
                      <Select
                        style={{ width: '100%' }}
                        placeholder="请选择是否收取材料"
                        onChange={this.onIsMatFlag}
                        allowClear
                        showSearch
                        filterOption={(input, option) =>
                          option.props.children.toLowerCase().indexOf(input.toLowerCase()) >= 0
                        }
                      >
                        <Option key="1">是</Option>
                        <Option key="2">否</Option>
                      </Select>
                    )}
                  </FormItem>
                </Col>
                <Col span={8}>
                  <FormItem {...formItemLayout} label={<span>备注</span>}>
                    {getFieldDecorator('remark', {
                      rules: [
                        {
                          required: false,
                          message: '请填写字数不超过100字的备注',
                          max: 100,
                        },
                      ],
                      initialValue: remark,
                    })(<Input placeholder="请填写字数不超过100字的备注" />)}
                  </FormItem>
                </Col>
              </Row>
              {String(coltFlag) === '2' ? (
                <span style={{ marginLeft: 14, color: '#f00' }}>
                  注：请确保实际业务办理中，无须向员工进行收取任何的纸质或电子文件，以及无须额外获取任何的人员的相关信息
                </span>
              ) : null}
            </Form>
          </Card>

          {String(coltFlag) === '1' &&
            tableArr.map((item, i) => (
              <Card bordered={false} style={{ marginBottom: 25 }} key={item.pageIdEdit}>
                <div className={materialStyle.warp}>
                  {/* 是否显示标题 this.state.titleArr[i] == true 显示标题，否则显示修改框   */}
                  <header>
                    {titleArr[i] ? (
                      <span className={materialStyle.header}>
                        {headertitle[i]}
                        <EditOutlined
                          className={materialStyle.icon}
                          onClick={() => {
                            this.changeTitle(i);
                          }}
                        />
                      </span>
                    ) : (
                      <span>
                        <Input
                          value={headertitle[i]}
                          maxLength={15}
                          onChange={e => {
                            this.changeValue(i, e.target.value);
                          }}
                        />
                        <a
                          style={{ marginLeft: 4 }}
                          onClick={() => {
                            this.headersave(i);
                          }}
                        >
                          保存
                        </a>
                      </span>
                    )}
                    {tableArr.length > 1 && (
                      <span
                        className={styles.titleEdit}
                        onClick={() => {
                          this.pageDelete(item.pageIdEdit, i);
                        }}
                      >
                        删除
                      </span>
                    )}
                  </header>
                  {/* defaultExpandAllRows必须是第一次渲染 */}
                  {item.maGpDetails && item.maGpDetails.length ? (
                    <Table
                      key={item.maGpDetails.length}
                      dataSource={item.maGpDetails}
                      columns={columns}
                      pagination={pagination}
                      rowKey={record => record.matId}
                      rowClassName={styles.editableRow}
                      defaultExpandAllRows
                      onRow={() => ({ onClick: () => this.rowData(i) })}
                    />
                  ) : (
                    <p style={{ marginTop: 18 ,marginLeft: 10}}>暂无数据</p>
                  )}
                  <Button
                    type="dashed"
                    style={{ margin: '10px 0px 10px 10px'}}
                    icon={<PlusOutlined />}
                    onClick={e => {
                      this.metrialbox(e, i);
                    }}
                  >
                    添加材料
                  </Button>
                </div>
              </Card>
            ))}
        </Spin>
        {String(coltFlag) === '2' ? null : (
          <Button
            type="dashed"
            style={{ width: '100%', height: 112, marginBottom: 200 }}
            icon={<PlusOutlined />}
            onClick={this.addTable}
            disabled={isDisabled}
          >
            添加分页
          </Button>
        )}

        <AddMatModal
          visMaterial={visMaterial}
          inputType={inputType}
          modelsData={inservicematerial}
          flagList={flagList}
          changeOkMaterial={this.changeOkMaterial}
          handleModalVisible={this.handleModalVisible}
          metrialLocalData={this.metrialLocalData}
          changeBig={this.changeBig}
        />

        <JudgeMatModal
          visJudge={visJudge}
          inputType={inputType}
          modelsData={inservicematerial}
          flagList={flagList}
          okJudge={this.okJudge}
          handleModalJudgeVisible={this.handleModalJudgeVisible}
          metrialLocalData={this.metrialLocalData}
          handleLogicChange={this.handleLogicChange}
          changeBig={this.changeBig}
        />

        <FooterToolbar>
          <Button onClick={this.submitcancel}>取消</Button>
          <Button type="primary" onClick={this.submitAll}>
            保存
          </Button>
        </FooterToolbar>
      </PageHeaderWrapper>
    );
  }
}
export default AddInservicematerials;
